﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace LinqToDB.Provider
{
    /// <summary>
    /// 表达式参数替换类
    /// </summary>
    class ExpresstionReplaceParam:ExpressionVisitor
    {
        /// <summary>
        /// 新旧参数对照字典
        /// </summary>
        Dictionary<ParameterExpression, Expression> m_replaceDic;
        /// <summary>
        /// 构造参数替换器
        /// </summary>
        /// <param name="replaceDic">参数替换字典</param>
        public ExpresstionReplaceParam(Dictionary<ParameterExpression, Expression> replaceDic)
        {
            m_replaceDic = replaceDic;
        }

        internal override Expression VisitMemberAccess(MemberExpression m)
        {
            Expression exp = this.Visit(m.Expression);
            if (exp != m.Expression)
            {
                NewExpression newExp = exp as NewExpression;
                if (newExp != null)
                { 
                    for(int i=0;i< newExp.Members.Count;i++)
                    {
                        var member = newExp.Members[i];
                        if (m.Member.Name == member.Name)
                        {
                            return newExp.Arguments[i];
                        }
                    }
                }
                return Expression.MakeMemberAccess(exp, m.Member);
            }
            return m;
        }

        /// <summary>
        /// 转换参数表达式
        /// </summary>
        /// <param name="p">参数表达式</param>
        /// <returns>转换后的表达式</returns>
        internal override Expression VisitParameter(ParameterExpression p)
        {
            if(m_replaceDic.ContainsKey(p))
                return m_replaceDic[p];
            return base.VisitParameter(p);
        }
    }
}
